home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C22 / MultipleInheritance3.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.1 KB  |  57 lines

  1. //: C22:MultipleInheritance3.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Virtual base initialization
  7. // Virtual base classes must always be
  8. // Initialized by the "most-derived" class
  9. #include "../purge.h"
  10. #include <iostream>
  11. #include <vector>
  12. using namespace std;
  13.  
  14. class MBase {
  15. public:
  16.   MBase(int) {}
  17.   virtual char* vf() const = 0;
  18.   virtual ~MBase() {}
  19. };
  20.  
  21. class D1 : virtual public MBase {
  22. public:
  23.   D1() : MBase(1) {}
  24.   char* vf() const { return "D1"; }
  25. };
  26.  
  27. class D2 : virtual public MBase {
  28. public:
  29.   D2() : MBase(2) {}
  30.   char* vf() const { return "D2"; }
  31. };
  32.  
  33. class MI : public D1, public D2 {
  34. public:
  35.   MI() : MBase(3) {}
  36.   char* vf() const {
  37.     return D1::vf(); // MUST disambiguate
  38.   }
  39. };
  40.  
  41. class X : public MI {
  42. public:
  43.   // You must ALWAYS init the virtual base:
  44.   X() : MBase(4) {}
  45. };
  46.  
  47. int main() {
  48.   vector<MBase*> b;
  49.   b.push_back(new D1);
  50.   b.push_back(new D2);
  51.   b.push_back(new MI); // OK
  52.   b.push_back(new X);
  53.   for(int i = 0; i < b.size(); i++)
  54.     cout << b[i]->vf() << endl;
  55.   purge(b);
  56. } ///:~
  57.